<template>
  <div :class="['role-container', `${prefixCls}-bg`]">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <i class="el-icon-plus"></i>
          </template>
          新增
        </el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <template #icon>
            <i class="el-icon-delete"></i>
          </template>
          删除
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入关键字搜索"
          prefix-icon="Search"
          clearable
        />
      </div>
    </div>

    <!-- 角色列表 -->
    <el-table
      :data="filteredRoleList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="roleKey" label="别名" />
      <el-table-column prop="sort" label="排序" width="100" />
      <el-table-column prop="status" label="开启状态" width="100">
        <template #default="{ row }">
          <el-switch v-model="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" link @click="handleConfigPermission(row)">配置权限</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="formData.id ? '编辑角色' : '新增角色'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="别名" prop="roleKey">
          <el-input v-model="formData.roleKey" placeholder="请输入别名" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.status" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置组件 -->
    <permission-config
      v-model="permissionDrawerVisible"
      :role="currentRole"
      @save="handleSavePermissions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  ElButton,
  ElInput,
  ElTable,
  ElTableColumn,
  ElSwitch,
  ElForm,
  ElFormItem,
  ElInputNumber,
  ElDialog
} from 'element-plus'

// 导入权限配置组件
import PermissionConfig from './components/PermissionConfig.vue'

// 引入样式
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/table/style/css'
import 'element-plus/es/components/table-column/style/css'
import 'element-plus/es/components/switch/style/css'
import 'element-plus/es/components/form/style/css'
import 'element-plus/es/components/form-item/style/css'
import 'element-plus/es/components/input-number/style/css'
import 'element-plus/es/components/dialog/style/css'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'

// 使用与 analytics 相同的前缀方式
const prefixCls = 'app'

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    roleName: '超级管理员',
    roleKey: 'SA',
    sort: 1,
    status: true
  },
  {
    id: 2,
    roleName: '管理员',
    roleKey: 'admin',
    sort: 2,
    status: true
  },
  {
    id: 3,
    roleName: '代理商',
    roleKey: 'agent',
    sort: 3,
    status: true
  }
])

// 搜索关键字
const searchKeyword = ref('')

// 过滤后的角色列表
const filteredRoleList = computed(() => {
  if (!searchKeyword.value) return roleList.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return roleList.value.filter(role => 
    role.roleName.toLowerCase().includes(keyword) ||
    role.roleKey.toLowerCase().includes(keyword)
  )
})

// 选中的行
const selectedRows = ref<any[]>([])

// 表单相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const formData = ref({
  id: '',
  roleName: '',
  roleKey: '',
  sort: 1,
  status: true,
  remark: ''
})

// 表单校验规则
const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleKey: [{ required: true, message: '请输入别名', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 处理表格选择
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 新增角色
const handleAdd = () => {
  formData.value = {
    id: '',
    roleName: '',
    roleKey: '',
    sort: roleList.value.length + 1,
    status: true,
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: any) => {
  formData.value = { ...row }
  dialogVisible.value = true
}

// 权限配置相关
const permissionDrawerVisible = ref(false)
const currentRole = ref<any>(null)

// 配置权限
const handleConfigPermission = (row: any) => {
  currentRole.value = row
  permissionDrawerVisible.value = true
}

// 保存权限配置
const handleSavePermissions = async (data: { roleId: number, permissions: string[] }) => {
  try {
    // TODO: 调用接口保存权限配置
    const role = roleList.value.find(item => item.id === data.roleId)
    if (role) {
      role.permissions = data.permissions
      ElMessage.success('权限配置已保存')
    }
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

// 删除角色
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      type: 'warning'
    })
    const index = roleList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      roleList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) return
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个角色吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    roleList.value = roleList.value.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    ElMessage.success('删除成功')
  } catch {
    // 取消删除
  }
}

// 保存角色
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formData.value.id) {
      // 编辑
      const index = roleList.value.findIndex(item => item.id === formData.value.id)
      if (index > -1) {
        roleList.value[index] = { ...formData.value }
      }
    } else {
      // 新增
      roleList.value.push({
        ...formData.value,
        id: Date.now()
      })
    }
    
    dialogVisible.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}
</script>

<style lang="less" scoped>
.role-container {
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .left {
    display: flex;
    gap: 10px;
  }
  
  .right {
    width: 200px;
  }
}

:deep(.el-table) {
  background-color: var(--el-bg-color);
  
  th.el-table__cell {
    background-color: var(--el-bg-color);
  }
  
  .el-table__cell {
    background-color: var(--el-bg-color);
  }
}

:deep(.el-dialog) {
  background-color: var(--el-bg-color);
  
  .el-dialog__header {
    color: var(--el-text-color-primary);
  }
  
  .el-form-item__label {
    color: var(--el-text-color-primary);
  }
  
  .el-input__wrapper,
  .el-textarea__inner {
    background-color: var(--el-bg-color);
  }
}
</style> 
